<template>
  <j-modal
    :confirmLoading='confirmLoading'
    :title='title'
    :visible='visible'
    :width='800'
    cancelText='关闭'
    switchFullscreen
    @cancel='handleCancel'
    @ok='handleOk'>
    <a-divider style='font-weight: 600;margin-top: 0px;' orientation='left'>基本信息</a-divider>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-col :md='12' :sm='24'>
          <a-form-item label='选择人员' v-if='!itemShow' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input-search v-decorator="['visitUserRealName',validatorRules.visitUserRealName]" placeholder='请选择协访人员'
                            :disabled='disableSubmit' enter-button readOnly @search="productSearch2('superiorUser')" />
            <a-input v-decorator="[ 'visitUserName', {}]" readOnly type='hidden' />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='人员职位'>
            <a-input v-decorator="['visitPosName']" :disabled='true' />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属组织'>
            <a-input v-decorator="['visitOrgName']" :disabled='true' />
          </a-form-item>
        </a-col>
        <a-col :md='12' :sm='24'>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="协访日期">
            <a-date-picker v-decorator="['visitDate', validatorRules.visitDate]" format="YYYY-MM-DD" style='width: 100%' valueFormat="YYYY-MM-DD" @change='dateTime' />
          </a-form-item>
        </a-col>
<!--        <a-col :md='12' :sm='24'>-->
<!--          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='循环日期'>-->
<!--            <a-range-picker :placeholder="['开始时间','结束时间']" :format="'YYYY-MM-DD'" :valueFormat="'YYYY-MM-DD'"-->
<!--                            v-decorator="['dataRange', validatorRules.dataRange]" @change='dateRangeChange'></a-range-picker>-->
<!--          </a-form-item>-->
<!--        </a-col>-->
        <a-divider orientation='left' style='font-weight: 600;margin-top: 0px;'>被协访人员拜访信息</a-divider>
          <div style='position: relative'>
            <a-form-model :model='forms'>
              <a-col :md='12' :sm='24'>
                <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='选择人员'>
                  <a-input-search v-model='forms.realname' :disabled='disableSubmit'
                                  enter-button placeholder='请选择被协访人员' readOnly @search="productSearch3('superiorUser')" />
                  <a-input v-model='forms.realname' readOnly type='hidden' />
                </a-form-model-item>
              </a-col>
              <a-col :md='12' :sm='24'>
                <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='人员职位'>
                  <a-input v-model='forms.positionName'  :disabled='true' />
                </a-form-model-item>
              </a-col>
              <a-col :md='12' :sm='24'>
                <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属组织'>
                  <a-input v-model='forms.orgName' :disabled='true' />
                </a-form-model-item>
              </a-col>
              <a-divider orientation='left' style='font-weight: 600;margin-top: 0px;'></a-divider>
              <a-tabs ref='tabs' defaultActiveKey='1' @change='cutType'>
                <a-tab-pane key='1' tab='客户'></a-tab-pane>
                <a-tab-pane key='2' tab='门店'></a-tab-pane>
              </a-tabs>
                <div>
                  <a-button style='margin: 10px 30px 0px 30px;' type='primary' @click='handleAdd'>新增</a-button>
                </div>
                <div style='padding: 10px 20px'>
                  <a-table
                    ref='table'
                    :columns='showType?columns2: columns'
                    :dataSource='showType?forms.dataSource2:forms.dataSource'
                    :loading='loading'
                    :pagination='showType?ipagination2:ipagination'
                    :rowSelection='{selectedRowKeys:showType? forms.selectedRowKeys2:forms.selectedRowKeys, onChange: onSelectChange}'
                    :scroll='{x:400,y:240 }'
                    bordered
                    rowKey='id'
                    size='middle'
                    @change='handleTableChange'>
            <span slot='action' slot-scope='text, record'>
               <a style='color: red;' @click='handleDelete(record)'>删除</a>
            </span>
                  </a-table>
                </div>
              <a-divider orientation='left' style='font-weight: 600;margin-top: 20px;'></a-divider>
            </a-form-model>
<!--            <a-button v-if='!disableSubmit' style='position: absolute;right: 0px;top: 45px;' type='primary'-->
<!--                      @click='clickToadd($event,index)'>{{ index == 0 ? '+' : '-' }}-->
<!--            </a-button>-->
          </div>
        <my-shuttle-modal
          ref='orgShuttleModal'
          :columns='orgColumns'
          :columns2='orgColumns2'
          :searchConfig='orgSearchConfig'
          :clientType='clientType'
          :visitDate='visitDate'
          :visitPosCode='visitPosCode'
          keyVal='clientCode'
          :leftUrl='jingxiaoshang'
          title='选择客户'
          @chooseOk='chooseOk'
        ></my-shuttle-modal>
        <my-shuttle-modal
          ref='cusShuttleModal'
          :columns='cusColumns'
          :columns2='cusColumns2'
          :searchConfig='cusSearchConfig'
          :clientType='clientType'
          :visitDate='visitDate'
          :visitPosCode='visitPosCode'
          keyVal='clientCode'
          :leftUrl='mendian'
          title='选择门店'
          @chooseOk='chooseOk2'
        ></my-shuttle-modal>
      </a-form>
    </a-spin>
    <proChose ref='prochoose2' :name="name" v-bind='modalProps' @okbro='okbropro2'></proChose>
    <proChose ref='prochoose3' v-bind='modalProps' @okbro='okbropro3'></proChose>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import myShuttleModal from '@/components/cn-components/CnShuttleModal'
import proChose from '@comp/cn-components/ProChose'
import JSelectUserPosition from '../../../../components/cn-select-popup/JSelectUserPosition'

export default {
  name: 'SfaVisitGroupModal',
  components: {
    JSelectUserPosition,
    proChose,
    myShuttleModal
  },
  data() {
    return {
      clientType: '',
      visitPosCode: '',//被协防人职位
      visitDate:'',//协防日期
      mendian: window._CONFIG['domianSfaURL'] + '/small/visit/sfaVisitLineEntity/findPageListSmall',
      jingxiaoshang: window._CONFIG['domianSfaURL'] + '/small/visit/sfaVisitLineEntity/findPageListSmall',
      index: '',
      objs: {},
      list:[],
      forms: {
        createBy: '',
        realname: "", //被协访人姓名
        positionName: "",  //职位名称
        visitPosCode: "",//被协防人职位
        orgName: "",  // 所属组织名
        departCode: '',//所属组织
        dataSource: [],
        dataSource2: [],
        selectedRowKeys: [],
        selectedRowKeys2: [],
      },
      store: [], //门店
      distributor: [], //客户
      cusColumns: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'clientName'
        }
      ],
      cusColumns2: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'clientName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      //门店弹窗查询
      cusSearchConfig: [
        {
          type: 'input',
          name: 'clientCode',
          placeholder: '门店编码'
        },
        {
          type: 'input',
          name: 'clientName',
          placeholder: '门店名称'
        },
      ],
      orgColumns: [
        {
          title: '客户编码',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'clientName'
        }
      ],
      orgColumns2: [
        {
          title: '客户编码',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'clientName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      // 客户查询
      orgSearchConfig: [
        {
          type: 'input',
          name: 'clientCode',
          placeholder: '客户编码'
        },
        {
          type: 'input',
          name: 'clientName',
          placeholder: '客户名称'
        },
      ],
      title: '操作',
      visible: false,
      showType: 0,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      productSearch2(status) {
        this.$refs.prochoose2.rowKey = 'id'
        let formconfig = [{
          key: 'userName',
          label: '用户账户'
        },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
            title: '用户账户',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',
          name:'协防人员',
          multiple: false,
          columW: 10
        }

        this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose2.isorter={  permflag: 'plan_making_add_user' }
        this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      productSearch3() {
          this.$refs.prochoose3.rowKey = 'id'
          let formconfig = [
            {
              key: 'username',
              label: '用户账户'
            },
            {
              key: 'realname',
              label: '用户名称'
            }
          ]
          let tableconfig = {
            columns: [{
              title: '用户账户',
              align: 'left',
              dataIndex: 'username',
              width: 120,
              ellipsis: true
            },
              {
                title: '用户名称',
                align: 'left',
                dataIndex: 'realname',
                width: 120,
                ellipsis: true
              }
            ],
            list: window._CONFIG['domianURL'] + '/cnPositionController/findSubordinatePositionList',
            positionCode: this.objs.positionCode,
            name:'被协防人员',
            multiple: false,
            columW: 10
          }
          this.name = '被协防人员'
          let dataSource = []
          // if (this.forms[this.index].getFieldValue('superiorUser')) {
          dataSource = [
            //   {
            //   userName: this.forms[this.index].getFieldValue('superiorUser'),
            //   realName: this.forms[this.index].getFieldValue('realsname')
            // }
          ]
          // }
          this.$refs.prochoose3.edit(formconfig, tableconfig, 'superiorUser', 'realsname')

      },
      validatorRules: {
        visitUserRealName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifyName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifytotName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        visitDate: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        dataRange:{
          rules: [{
            required: true,
            message: ''
          }]
        },
        groupName: {
          rules: [{
            required: true,
            message: ''
          }]
        }
      },
      dataSource: [],//客户
      dataSource2: [],//门店
      fileList: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        }
      },
      columns: [
        {
          title: '客户编号',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'clientName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      columns2: [
        {
          title: '门店编号',
          align: 'center',
          dataIndex: 'clientCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'clientName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],

      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/saveVisit'
      }
    }
  },
  created() {
  },
  methods: {
    dateRangeChange(e){
      console.log(e)
    },
    dateTime(e){
      console.log(e)
      this.visitDate = e
    },
    add() {
      this.form.resetFields()
      this.visible = true
    },
    cutType(key) {
      if (key == '1') {
        this.showType = false
        this.clientType = 2

      } else {
        this.showType = true
        this.clientType = 1
      }
    },
    handleDelete(e) {
      if (this.showType) {
        let key = this.forms.dataSource2.map(item => {
          return item.id
        })
        this.forms.dataSource2.splice(key.indexOf(e.id), 1)
      } else {
        let key = this.forms.dataSource.map(item => {
          return item.id
        })
        this.forms.dataSource.splice(key.indexOf(e.id), 1)
      }

  },
  chooseOk(e) {
    console.log(this.index)
    this.forms.dataSource = []
    let key = this.forms.dataSource.map(item => {
      return item.code
    })
    console.log(e)
    let that = this
    e.forEach(item => {
      if (key.indexOf(item.custCode) == -1) {
        item.code = item.custCode
        item.name = item.custName
        this.forms.dataSource.push(item)
      }
    })
  },
  chooseOk2(e) {
    this.forms.dataSource2 = []
    let key = this.forms.dataSource2.map(item => {
      return item.code
    })
    console.log(e)
    let that = this
    e.forEach(item => {
      if (key.indexOf(item.clientCode) == -1) {
        this.forms.dataSource2.push(item)
      }
    })

  },
  onSelectChange(selectedRowKeys, selectionRows) {
    if (this.showType) {
      this.forms.selectedRowKeys2 = selectedRowKeys
      this.forms.selectionRows2 = selectionRows
    } else {
      this.forms.selectedRowKeys = selectedRowKeys
      this.forms.selectionRows = selectionRows
    }
  },
  handleAdd() {
    if(this.visitPosCode!=''){
      if(this.visitDate!=''){
    if (this.showType) {
      this.forms.dataSource.forEach(item => {
        this.$refs.cusShuttleModal.dataSource2.push({
          clientCode: item.clientCode,
          clientName: item.clientName
        })
        this.$refs.cusShuttleModal.selectionRows.push({
          clientCode: item.clientCode,
          clientName: item.clientName
        })
        this.$refs.cusShuttleModal.selectedRowKeys.push(item.clientCode)
      })
      this.$refs.cusShuttleModal.visible = true
      this.$refs.cusShuttleModal.loadData()
    } else {
      this.forms.dataSource2.forEach(item => {
        this.$refs.orgShuttleModal.dataSource2.push({
          clientCode: item.clientCode,
          clientName: item.clientName
        })
        this.$refs.orgShuttleModal.selectionRows.push({
          clientCode: item.clientCode,
          clientName: item.clientName
        })
        this.$refs.orgShuttleModal.selectedRowKeys.push(item.clientCode)
      })
      this.$refs.orgShuttleModal.visible = true
      this.$refs.orgShuttleModal.loadData()
    }
    }else{
      this.$message.warning('请选择有效期')
    }
  }else{
    this.$message.warning('请选择被协访人员')
  }
  },
  edit(record) {
    this.form.resetFields()
    this.model = Object.assign({}, record)
    this.visible = true
    this.$nextTick(() => {
      this.form.setFieldsValue(pick(this.model, ' visitAssistUserRealName', 'createDate', 'createDateTime', 'updateDate', 'updateDateTime', 'updateName', 'visitAssistPosCode', 'visitPosName', 'custCode', 'custName', 'status', 'deleteStatus', 'remarks', 'saasid', 'groupCode', 'groupName', 'visitPosCode', 'visitPosName', 'username', 'fullName', 'visitAssistOrgCode', 'visitAssistOrgName', 'untitled1', 'untitled'))
      //时间格式化
    })

  },
  okbropro2(val) {
    console.log(val)
    let oldDate = this.objs.realName
    let objs = JSON.parse(JSON.stringify(val[0]))
    this.objs = objs
    this.form.setFieldsValue({
      visitUserName: objs.userName,
      visitUserRealName: objs.realName,
      visitPosName: objs.positionName,
      visitPosCode: objs.positionCode,
      visitOrgName: objs.departName,
      visitOrgCode: objs.departCode
    })
    console.log(this.objs.realName)
    // 协防人修改，旗下被协防人数据清空
    if (oldDate !== this.objs.realName) {
      this.forms = {
        createBy: '',
        realname: "",
        positionName: "",
        orgName: "",
        dataSource: [],
        dataSource2: [],
      }
      this.list=[]
    }
  },
  okbropro3(val, status, status2) {
    let objs = JSON.parse(JSON.stringify(val[0]))
    console.log(objs)
    this.forms.createBy = objs.username
    this.forms.realname = objs.realname
    this.forms.visitUserRealName = objs.realName
    this.forms.positionName = objs.positionName
    this.visitPosCode = objs.positionCode
    this.forms.orgName = objs.orgName
    this.forms.departCode = objs.orgCode
  },
  close() {
    this.$emit('close')
    this.visible = false
    this.forms =
      {
        createBy: '',
        realname: "",
        visitAssistPosName: "",
        orgName: "",
        dataSource: [],
        dataSource2: [],
      }
      this.list=[]
  },
  handleOk() {
    const that = this
    // 触发表单验证
    console.log(this.store,this.forms)
    let dataSource = this.forms.dataSource.map(type => Object.assign({
      visitAssistOrgCode:this.forms.departCode,
      visitAssistOrgName:this.forms.orgName,
      visitAssistPosCode:this.forms.visitPosCode,
      visitAssistPosName:this.forms.positionName,
      visitAssistUserRealName:this.forms.realname,
      visitAssistUserName:this.forms.createBy,
      clientCode: type.clientCode,
      clientName: type.clientName,
      lng: type.lng,
      lat: type.lat,
      clientAddress: type.address,
      // assistId:type.id,
      id:type.id,
      visitDateStart:type.visitDateStart,
      visitDateEnd:type.visitDateEnd,
      clientType: 2
    }))
    let dataSource2 = this.forms.dataSource2.map(type => Object.assign({
      visitAssistOrgCode:this.forms.departCode,
      visitAssistOrgName:this.forms.orgName,
      visitAssistPosCode:this.forms.positionCode,
      visitAssistPosName:this.forms.positionName,
      visitAssistUserRealName:this.forms.realname,
      visitAssistUserName:this.forms.createBy,
      clientCode: type.clientCode,
      clientName: type.clientName,
      clientAddress: type.address,
      // assistId:type.id,
      id:type.id,
      lng: type.lng,
      lat: type.lat,
      visitDateStart:type.visitDateStart,
      visitDateEnd:type.visitDateEnd,
      clientType: 1
    }))
    this.list = dataSource2.concat(...dataSource)
    this.form.validateFields((err, values) => {
      if (!err) {
        that.confirmLoading = true
        let httpurl = ''
        let method = ''
        httpurl += this.url.add
        method = 'post'

        let formData = Object.assign(this.model, values)
        formData.list = this.list
        formData.visitPosCode = this.objs.positionCode
        formData.orgCode = this.objs.departCode
        formData.operType = 1
        //时间格式化
        httpAction(httpurl, formData, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.confirmLoading = false
          that.close()
        })
      }
    })
  },
  handleTableChange(pagination, filters, sorter) {
    //分页、排序、筛选变化时触发
    //TODO 筛选
    if (Object.keys(sorter).length > 0) {
      this.isorter.column = sorter.field
      this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
    }
    if (this.ipagination.current !== pagination.current) {
      this.selectionRows = []
      this.selectedRowKeys = []
    }
    this.ipagination = pagination
    // this.loadData()
  },
  handleCancel() {
    this.form.resetFields()
    this.visible = false
    this.fileList = []
    this.confirmLoading = false
    this.dataSource = []
    this.dataSource2 = []
    this.close()
  }
  // handleCancel () {
  //   this.close()
  // },
}

}
</script>

<style lang='less' scoped>

</style>
